<?php

Yii::import('apps.prestige.modules.tickets.models._base.BaseTicket');

class Ticket extends BaseTicket
{
	const NOTIFICATION_TYPE_NEW = 'new';
	const NOTIFICATION_TYPE_UPDATED = 'updated';
	const NOTIFICATION_TYPE_ESCALATED = 'escalated';
	const NOTIFICATION_TYPE_CLOSED = 'closed';
	
	public static function model($className=__CLASS__) {
		return parent::model($className);
	}
	
	public function behaviors(){
		return array(
			'CTimestampBehavior' => array(
				'class' => 'zii.behaviors.CTimestampBehavior',
				'createAttribute' => 'create_time',
				'updateAttribute' => 'update_time',
			)
		);
	}
	
	public function sendNotificationEmail($type, $extraInfo = array())
	{
		//$agency = $this->agency_id;
		$agency = Agency::model()->findByAttributes(array('id'=>$this->agency_id));
		$notificationName = $agency->name;
		$notificationEmail = $agency->admin_email;
		if ($notificationEmail == null) {
			$notificationName = Yii::app()->params["notificationsName"];
			$notificationEmail = Yii::app()->params["notificationsEmail"];
		}

		// prepare mailer
		$mailer = new Mailer();
		$mailer->From = $notificationEmail;
		$mailer->FromName = $notificationName;
		$mailer->AddAddress($this->email, $this->name);

		switch ($type) {
			case self::NOTIFICATION_TYPE_NEW:
				$mailer->Subject = 'Ticket Opened [#' . $this->ticket_code . ']';
				break;
			case self::NOTIFICATION_TYPE_UPDATED:
				$mailer->Subject = 'Ticket Updated [#' . $this->ticket_code . ']';
				break;
			case self::NOTIFICATION_TYPE_CLOSED:
				$mailer->Subject = 'Ticket Closed [#' . $this->ticket_code . ']';
				break;
			case self::NOTIFICATION_TYPE_ESCALATED:
				$mailer->Subject = 'Ticket Escalated [#' . $this->ticket_code . ']';
				break;
		}
		
		$hostname =	Yii::app()->request->hostInfo;
		
		$tokens = $this->attributes;
		$tokens['agency_name'] = $agency->name;
		$tokens['ticket_link'] = $hostname . '/' . $agency->shortname . '/tickets/view/ticket_code/' . $this->ticket_code . '/email/' . $this->email;
		
		$tokens = array_merge($tokens, $extraInfo);

		$mailer->createHTMLMail(Yii::getPathOfAlias('common') . "/templates/emails/tickets/html/" . $type . ".tpl", $tokens);
		$mailer->createTEXTMail(Yii::getPathOfAlias('common') . "/templates/emails/tickets/text/" . $type . ".tpl", $tokens);
				
		return $mailer->sendMail();
	}
	
}